/**
 * 
 */
package com.pzitsoft.videoteca.dao.hibernate;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.pzitsoft.videoteca.dao.DBTemplate;



/**
 * @author pferraz
 *
 */
public class DBObject {
	private static Logger logger=Logger.getLogger(DBObject.class);
	
	
	public DBObject(){}
	
	public static boolean addObject(Object o){
		Session sess=null;
		Transaction tx=null;
		try{
			sess=DBTemplate.getConnTemplate().getSessionFactory().openSession();
			tx=sess.beginTransaction();
			sess.save(o);
			tx.commit();
		}catch(HibernateException e){
			logger.error("Error al persistir objeto " + o.getClass(),e);
			tx.rollback();
			return false;
		}finally {
			try{
            if (sess != null){
                sess.close();
            }
			}catch(Exception e){
				logger.error(e);
			}
        }		
		return true;
	}
	
	public static boolean updateObject(Object o){
		Session sess=null;
		Transaction tx=null;
		try{
			sess=DBTemplate.getConnTemplate().getSessionFactory().openSession();
			tx=sess.beginTransaction();
			sess.update(o);
			tx.commit();
			return true;
		}catch(HibernateException e){
			logger.error("Error al actualizar "+ o.getClass(),e);
			tx.rollback();
			return false;
		}finally {
            if (sess != null){
            	sess.close();
            }
                
        }
	}
	
	public static boolean removeObject(Object o){
		Session sess=null;
		Transaction tx=null;
		try{
			sess=DBTemplate.getConnTemplate().getSessionFactory().openSession();
			tx=sess.beginTransaction();
			sess.delete(o);
			tx.commit();
			return true;
		}catch(HibernateException e){
			logger.error("Error al elminar dato",e);
			tx.rollback();
			return false;
		}finally{
			if(sess!=null){
				sess.close();
			}
		}
	}
}
